package com.dsx.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dsx.commons.result.Result;
import com.dsx.dto.LoginDto;
import com.dsx.entity.User;
import com.dsx.service.UserService;
import com.dsx.utils.JwtUtils;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author dsx
 * @date 2021/3/31 12:44
 * @since JDK1.8
 */
@RestController
public class AccountController {
    @Autowired
    UserService userService;
    
    @Autowired
    JwtUtils jwtUtils;

    /**
     * 默认账号密码：markerhub / 111111
     *
     */
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response){
        System.err.println(loginDto.toString());
        User dbuser = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));

        Assert.notNull(dbuser,"用户不存在");

        System.out.println(!dbuser.getPassword().equals(SecureUtil.md5(loginDto.getPassword())));
        if (!dbuser.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
            return Result.fail("密码不正确");
        }
        String jwtToken = jwtUtils.generateToken(dbuser.getId());//将userId传递给jwttoken的Subject字段
        //只是对jwttoken延期有用，如果不延期可以不设置。
        response.setHeader("Authorization",jwtToken);
        response.setHeader("Access-Control-Expose-Headers","Authorization");
        return Result.success(MapUtil.builder()
                .put("id",dbuser.getId())
                .put("username",dbuser.getUsername())
                .put("password",dbuser.getPassword())
                .put("avatar",dbuser.getAvatar())
                .put("email",dbuser.getEmail()).map());
    }

    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        System.err.println(request.getHeader("Authorization"));
       
        SecurityUtils.getSubject().logout();
       
        return Result.success(null);
    }
}
